#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test script to verify histogram_suffixes table deletion
"""

import sqlite3
import sys
import tempfile
import os

# Add the extractor directory to the path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from uma_ukm_extractor import DatabaseManager, HistogramInfo


def test_histogram_suffixes_removal():
    """Test that histogram_suffixes table was successfully removed."""

    # Create a temporary database
    with tempfile.NamedTemporaryFile(suffix='.db', delete=False) as temp_file:
        temp_db = temp_file.name

    try:
        print(f"Testing with temporary database: {temp_db}")

        # Create database manager
        db_manager = DatabaseManager(temp_db)
        db_manager.connect()
        db_manager.create_tables()

        print("✅ Database tables created successfully")

        # Check that histogram_suffixes table does not exist
        conn = sqlite3.connect(temp_db)
        cursor = conn.cursor()

        # Get list of all tables
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
        tables = [row[0] for row in cursor.fetchall()]

        print(f"📋 Created tables: {', '.join(tables)}")

        # Verify histogram_suffixes is not in the list
        if 'histogram_suffixes' in tables:
            print("❌ ERROR: histogram_suffixes table still exists!")
            return False
        else:
            print("✅ histogram_suffixes table successfully removed")

        # Verify other essential tables still exist
        essential_tables = ['metrics', 'histogram_details', 'enum_values', 'tokens', 'variants']
        missing_tables = [table for table in essential_tables if table not in tables]

        if missing_tables:
            print(f"❌ ERROR: Missing essential tables: {missing_tables}")
            return False
        else:
            print("✅ All essential tables present")

        # Test basic functionality - insert a histogram
        test_histogram = HistogramInfo(
            name="TestHistogram.AfterCleanup",
            summary="Test histogram after suffixes removal",
            file_path="test/histograms.xml",
            line_number=10,
            owners=["test@example.com"]
        )

        hist_id = db_manager.insert_histogram(test_histogram)
        print(f"✅ Successfully inserted test histogram with ID: {hist_id}")

        # Verify the data was inserted correctly
        cursor.execute("SELECT name, summary FROM metrics WHERE id = ?", (hist_id,))
        result = cursor.fetchone()

        if result and result[0] == "TestHistogram.AfterCleanup":
            print("✅ Database insertion and retrieval working correctly")
        else:
            print("❌ ERROR: Database insertion/retrieval failed")
            return False

        conn.close()
        db_manager.close()

        print("\n🎉 All tests passed! histogram_suffixes table successfully removed without affecting functionality.")
        return True

    except Exception as e:
        print(f"❌ Test failed: {e}")
        import traceback
        traceback.print_exc()
        return False
    finally:
        # Clean up
        if os.path.exists(temp_db):
            os.unlink(temp_db)
            print(f"🧹 Cleaned up temporary database: {temp_db}")


if __name__ == "__main__":
    print("Testing histogram_suffixes table removal...")
    print("=" * 60)

    success = test_histogram_suffixes_removal()

    if success:
        print("\n✅ All tests passed!")
        sys.exit(0)
    else:
        print("\n❌ Tests failed!")
        sys.exit(1)